package com.qfoud.edu.shiro.framwork.manager.impl;

import com.qfoud.edu.shiro.framwork.auth.AuthticationInfo;
import com.qfoud.edu.shiro.framwork.encoder.base.Encoder;
import com.qfoud.edu.shiro.framwork.encoder.impl.DefaultPasswordEncoder;
import com.qfoud.edu.shiro.framwork.manager.AuthticationManager;
import static com.qfoud.edu.shiro.framwork.pojo.Context.*;

import com.qfoud.edu.shiro.framwork.pojo.Context;
import com.qfoud.edu.shiro.framwork.pojo.Subject;
import com.qfoud.edu.shiro.framwork.result.LoginResultNotify;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author xiaobobo
 * @title: AuthticationManagerImpl
 * @projectName cd-java-2303-project-parent
 * @description: 用户认证的这个位置
 * @date 2023/5/11  15:35
 */
public class AuthticationManagerImpl implements AuthticationManager {

    //申明我们的密码的比较器
    private Encoder encoder=new DefaultPasswordEncoder();

    public Subject auth(AuthticationInfo authticationInfo, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //从前端传入的对象中获取用户名
        String username = authticationInfo.getUsername();
        //这里就踢皮球给开发人员  开发人员就要不要命的去查询数据库的数据
        Subject subject = getUserDetailService().loadUserByName(username);
        //接下来就是比较密码是否一致了....
        boolean matcher = encoder.matcher(authticationInfo.getPassword(), subject.getAuthticationInfo().getPassword());
        if(!matcher){
          //说明密码不一致
          getLoginResultNotify().fail(servletRequest,servletResponse);
          return null;
        }
        //程序执行到这里 说明密码是对的
        //通知用户登陆成功
        //假设我们就先不回调了
        //添加信息到Session中去
        addInfoToSession(servletRequest,username,subject);
        //回调到程序中告诉他登陆成功....
        LoginResultNotify loginResultNotify = Context.getLoginResultNotify();
        if(null!=loginResultNotify){
            loginResultNotify.success(servletRequest,servletResponse);
        }
        return subject;
    }

    /**
     * 添加信息到Session中去
     * @param servletRequest
     */
    private void addInfoToSession(ServletRequest servletRequest,String username,Subject subject) {
        //获取request对象
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        //这里获取Session对象
        HttpSession httpSession=req.getSession();
        //接下来向Session中写入 标记
        httpSession.setAttribute("user","xxxxx");
        //还需要将用户名放进去
        httpSession.setAttribute("username",username);
        //接下来需要将权限信息和角色信息放到Session中去
        List<String> perms = subject.getPerms();
        List<String> roles = subject.getRoles();
        //接下来需要将信息写入到Session中
        httpSession.setAttribute("perms",perms);
        httpSession.setAttribute("roles",roles);
    }
}
